package dfl.bysj.controller.push;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import dfl.bysj.config.RedisKey;
import dfl.bysj.config.model.AccessToken;
import dfl.bysj.config.model.VO.UserDto;
import dfl.bysj.entity.Floor;
import dfl.bysj.entity.HonestGrade;
import dfl.bysj.entity.Seat;
import dfl.bysj.entity.StudentSeatRelation;
import dfl.bysj.entity.VO.ReserveSUCCVO;
import dfl.bysj.service.FloorService;
import dfl.bysj.service.SeatService;
import dfl.bysj.service.SeatStateService;
import dfl.bysj.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @Author: DFL
 * 目的：配合定时任务做推送
 * 1、快到签到时，
 * @Data: 2022/5/715:07
 */
@Slf4j
@Component
@PropertySource("classpath:application.yml")
public class SendMessage {

    private static RedisTemplate redisTemplate;

    @Autowired
    public void setRedisTemplate(RedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    private static SeatService seatService;

    @Autowired
    public void setSeatService(SeatService seatService) {
        this.seatService = seatService;
    }

    private static FloorService floorService;

    private SeatStateService seatStateService;

    @Autowired
    public void setSeatStateService(SeatStateService seatStateService) {
        this.seatStateService = seatStateService;
    }

    private UserService userService;

    @Autowired
    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    @Autowired
    public void setFloorService(FloorService floorService) {
        this.floorService = floorService;
    }

    @Value("${wx.appid}")
    private String appid;

    @Value("${wx.secret}")
    private String secret;

    @Value("${wx.template_id_reserveSUCC}")
    private String template_id_reserveSUCC;

    @Value("${wx.template_id_signLost}")
    private String template_id_signLost;

    @Value("${wx.template_id_signBack}")
    private String template_id_signBack;

    @Value("${wx.template_id_sign}")
    private String template_id_sign;


    private String basePush(String template_id,String token,String openId,Map<String,Map> data){
        String open_id;
        if (token==null){
            open_id=openId;
        }else{
            open_id=getOpenId(token);
        }

        String url="https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token="+getAccessToken();
        Map<String,Object> params=new HashMap<>();
        params.put("touser",open_id);
        params.put("template_id",template_id);
        params.put("page", "pages/index_lib/index_lib");
        params.put("data",data);
        String json=JSON.toJSONString(params);
        log.info(json);
        String res=HttpUtil.post(url,json);
        log.info(res);
        return res;
    }

    public String pushReserveSUCC(String token, ReserveSUCCVO reserveSUCCVO){

        Map map=getFloSea(seatStateService
                .getById(reserveSUCCVO
                        .getSeaStaId()).getSeaId());
        String floSea=map.get("floNum")+"楼"+map.get("seaNum")+"号位";

        Map<String,Map> data=new LinkedHashMap<>();
        Map<String,String> map1=new HashMap<>();
        map1.put("value",floSea);
        Map<String,String> map2=new HashMap<>();
        map2.put("value",reserveSUCCVO.getResStartTime());
        Map<String,String> map3=new HashMap<>();
        map3.put("value",reserveSUCCVO.getResEndTime());

        data.put("thing2",map1);
        data.put("time11", map2);
        data.put("time12", map3);

       return  basePush(template_id_reserveSUCC,token,null,data);
    }

    public void pushSign(StudentSeatRelation s,String notice) {

        //获取openid
        String openId=userService.getOpenIdByStuUseId(s.getStuUseId());
        //获取座位
        Map map=getFloSea(seatStateService.getById(s.getSeaStaId()).getSeaId());
        String floSea=map.get("floNum")+"楼"+map.get("seaNum")+"号位";

        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String date=s.getResStartTime().format(dtf);

        Map<String,Map> data=new LinkedHashMap<>();
        Map<String,String> map1=new HashMap<>();
        map1.put("value", floSea);
        Map<String,String> map2=new HashMap<>();
        map2.put("value", date);
        Map<String,String> map3=new HashMap<>();
        map3.put("value",notice);


        data.put("thing2",map1);
        data.put("time11", map2);
        data.put("thing7", map3);


        basePush(template_id_sign,null,openId,data);
    }
    public String pushSignLost(StudentSeatRelation s, HonestGrade signLost){
        log.info("pushSignLost...........");
        //获取openId
        String openId=userService.getOpenIdByStuUseId(s.getStuUseId());
        //获取座位


        LocalDateTime localDateTime=LocalDateTime.now();
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String date=localDateTime.format(dtf);

        Map map=getFloSea(seatStateService.getById(s.getSeaStaId()).getSeaId());
        String floSea=map.get("floNum")+"楼"+map.get("seaNum")+"号位";

        Map<String,Map> data=new LinkedHashMap<>();
        Map<String,String> map1=new HashMap<>();
        map1.put("value", floSea);
        Map<String,String> map2=new HashMap<>();
        map2.put("value", date);
        Map<String,String> map3=new HashMap<>();
        map3.put("value","当前座位已释放，如有需要请重新预约");
        Map<String,String> map4=new HashMap<>();
        map4.put("value","当前的信用分数为："+signLost.getGrade());

        data.put("thing2",map1);
        data.put("time6", map2);
        data.put("thing1", map3);
        data.put("thing7", map4);


        return basePush(template_id_signLost,null,openId,data);
    }

    private String getOpenId(String token){
        UserDto userDto= (UserDto) redisTemplate.opsForValue().get(RedisKey.TOKEN+token);
        return userDto.getUser().getOpenId();
    }

    private Map<String, Integer> getFloSea(Integer seaId){
       Seat seat=seatService.getSeaNumBySeaId(seaId);
       Floor floor=floorService.getFloorByfloId(seat.getFloId());
       Map<String, Integer> res=new HashMap<>();
       res.put("floNum", floor.getFloNum());
       res.put("seaNum", seat.getSeaNum());
       return res;
    }

    private String getAccessToken(){

        Map<String,String> map=new HashMap<>();

        String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={0}&secret={1}";
        log.info(appid);
        log.info(secret);
        url = url.replace("{0}", appid).replace("{1}", secret);
        String res = HttpUtil.get(url);
        AccessToken accessToken= JSON.parseObject(res, AccessToken.class);
        log.info(accessToken.toString());
        return  accessToken.getAccess_token();
    }


    public void pushSignBackLost(StudentSeatRelation s, HonestGrade signBackLost) {
    }
}
